/**
 *
 * Copyright 2015 RSVP Technologies Inc. All rights reserved.
 * RouteSearch.java
 *
 */
package com.gfinal.map.direction;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gfinal.map.common.Constant;
import com.gfinal.map.util.HttpUtils;
import com.gfinal.map.util.Print;

/**
 * 公交、驾车、步行线路搜索
 * 
 * @author Gao Yudong (gyd@nbicc.com)
 * @date 2015-2-27
 */
public class RouteSearch {
	private static final String TAG = RouteSearch.class.getName();

	private String origin = null;
	private String destination = null;
	/*
	 * 导航模式，包括：driving（驾车）、walking（步行）、transit（公交）
	 */
	private String mode = "driving";
	private String region = "全国";
	private String origin_region = "全国";
	private String destination_region = "全国";

	/*
	 * 导航策略。导航路线类型，10，不走高速；11、最少时间；12、最短路径。
	 */
	private int tactics = 10;

	public void setOrigin(String origin) {
		this.origin = origin;
	}

	public void setDestination(String destination) {
		this.destination = destination;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public void setRegion(String region) {
		this.region = region;
	}

	public void setOrigin_region(String origin_region) {
		this.origin_region = origin_region;
	}

	public void setDestination_region(String destination_region) {
		this.destination_region = destination_region;
	}

	public void setTactics(int tactics) {
		this.tactics = tactics;
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private String createURI() {
		ArrayList params = new ArrayList();
		params.add(new BasicNameValuePair("origin", origin));
		params.add(new BasicNameValuePair("destination", destination));
		params.add(new BasicNameValuePair("mode", mode));
		params.add(new BasicNameValuePair("region", region));
		params.add(new BasicNameValuePair("origin_region", origin_region));
		params.add(new BasicNameValuePair("destination_region",
				destination_region));
		params.add(new BasicNameValuePair("output", "json"));
		params.add(new BasicNameValuePair("coord_type", "bd09ll"));
		params.add(new BasicNameValuePair("tactics", String.valueOf(tactics)));
		params.add(new BasicNameValuePair("ak", Constant.BAIDU_AK));
		return Constant.DIRECTION_URL + "?"
				+ URLEncodedUtils.format(params, Constant.CHARSET);
	}

	@SuppressWarnings("null")
	public DirectionBean execute() {
		DirectionBean result = new DirectionBean();
		String response = HttpUtils.doGet(createURI());
		JSONObject obj = JSON.parseObject(response);
		JSONObject resultObj = obj.getJSONObject("result");
		result.setMode(mode);
		if (obj.getIntValue("status") == 0) {
			int type = obj.getIntValue("type");
			if (type == 1) { // 起终点模糊
				result.setType(1);
				Candidate originCandidate = new Candidate();
				Candidate destinationCandidate = new Candidate();

				JSONObject originInfo = resultObj.getJSONObject("originInfo");
				JSONObject destinationInfo = resultObj
						.getJSONObject("destinationInfo");
				String originWd = originInfo.getString("wd");
				String destinationWd = destinationInfo.getString("wd");

				if (mode.equalsIgnoreCase("transit")) {
					JSONArray originArr = resultObj.getJSONArray("origin");
					JSONArray destinationArr = resultObj
							.getJSONArray("destination");
					if (originArr != null) {
						originCandidate.setContent(JSON.parseArray(
								originArr.toJSONString(), Content.class));
					}
					if (destinationArr != null) {
						destinationCandidate.setContent(JSON.parseArray(
								destinationArr.toJSONString(), Content.class));
					}
				} else {
					JSONObject origin = resultObj.getJSONObject("origin");
					JSONObject destination = resultObj
							.getJSONObject("destination");
					originCandidate = JSON.parseObject(origin.toJSONString(),
							Candidate.class);
					destinationCandidate = JSON.parseObject(
							destination.toJSONString(), Candidate.class);
				}
				originCandidate.setInput(originWd);
				destinationCandidate.setInput(destinationWd);
				result.setOriginCandidate(originCandidate);
				result.setDestinationCandidate(destinationCandidate);
			} else if (type == 2) { // 起终点唯一
				result.setType(2);
				if (mode.equalsIgnoreCase("transit")) {
					if (resultObj.containsKey("routes")) {
						JSONArray routesArr = resultObj.getJSONArray("routes");
						List<ArrayList<Scheme>> schemeList = new ArrayList<ArrayList<Scheme>>();
						for (int i = 0; i < routesArr.size(); i++) {
							JSONObject scheme = routesArr.getJSONObject(i);
							String schemeJson = scheme.getString("scheme");
							schemeList.add((ArrayList<Scheme>) JSON.parseArray(
									schemeJson, Scheme.class));
						}
						result.setScheme(schemeList);
					}
				} else {
					if (resultObj.containsKey("routes")) {
						result.setRoutes(JSON.parseArray(
								resultObj.getString("routes"), Route.class));
					}
				}

				if (resultObj.containsKey("taxi")) {
					result.setTaxi(JSON.parseObject(
							resultObj.getString("taxi"), Taxi.class));
				}

				if (resultObj.containsKey("traffic_condition")) {
					result.setTraffic_condition(resultObj
							.getIntValue("traffic_condition"));
				}

				if (resultObj.containsKey("origin")) {
					result.setOrigin(JSON.parseObject(
							resultObj.getString("origin"), StartEnd.class));
				}

				if (resultObj.containsKey("destination")) {
					result.setDestination(JSON.parseObject(
							resultObj.getString("destination"), StartEnd.class));
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		RouteSearch search = new RouteSearch();
		search.setOrigin("联升佳苑");
		search.setDestination("天一广场步行街");
		search.setMode("transit");
		search.setOrigin_region("宁波");
		search.setDestination_region("宁波");
		search.setRegion("宁波");
		search.setTactics(11);
		DirectionBean direction = search.execute();
		if (direction.getType() == 1) {
			Print.pln(TAG, direction.getOriginCandidate());
			Print.pln(TAG, direction.getDestinationCandidate());
		} else if (direction.getType() == 2) {
			Print.pln(TAG, direction.getTaxi());
			Print.pln(TAG, direction.getTraffic_condition());
			Print.pln(TAG, direction.getOrigin().getWd());
			Print.pln(TAG, direction.getDestination().getWd());
			if (direction.getMode().equalsIgnoreCase("transit")) {
				Print.pln(TAG, direction.getScheme());
			} else {
				Print.pln(TAG, direction.getRoutes());
			}
		}
	}
}
